//加载express模块
const express = require('express');
//声明express的Router方法
const router = express.Router();
const Category = require('../models/Category')
const Content = require('../models/Content')

//首页

router.get('/', function(req, res, next) {

  let userInfo = req.cookies.userInfo || {}
  let categoryId = req.query.categoryId || ''

  // 指定从数据库查找哪一分类
  let where = {}
  if(categoryId) where.category = categoryId
  Category
    .find()
    .then(function(categories) {
      Content
        .where(where)
        .count()
        .then(function(count) {
          // 限制每页获取的数据条数
          let limit = 5
          let pages = Math.ceil(count / limit)
          let page = parseInt(req.query.page || 1)
          let skip = (page - 1) * limit
          Content
            .where(where)
            .find()
            .sort({_id: -1})
            .populate('category')
            .limit(limit)
            .skip(skip)
            .then(function(contents) {
              res.render('home/index', {
                userInfo: userInfo,
                categories: categories,
                contents: contents,
                page: page,
                pages: pages,
                limit: limit,
                categoryId: categoryId
              })
            })
            return
        })
        return
    })
    return
})

router.get('/view', function(req, res, next) {

  let userInfo = req.cookies.userInfo || {}
  let contentId = req.query.contentId || ''

  if(contentId) {
    Category
      .find()
      .then(function(categories) {
        Content
          .findOne({_id: contentId})
          .populate('category')
          .then(function(content) {
            content.views++
            content.save()
            res.render('home/view', {
              categories: categories,
              content: content,
              categoryId: content.category.id,
              userInfo: userInfo
            })
          })
          return
      })
      return
  }
})

module.exports = router;